<template>
  <div id="pieBar" ref="pieBar" class="pie-bar"></div>
</template>
<script>
import { resizeChart, PieBarOptions } from "@/assets/js/echartOptions.js";
export default {
  name: "PieBar",
  data() {
    return {
      chart: null,
      options: null,
      colors: [
        ["#35a3fc", "#35a3fc"],
        ["#1459d9", "#1459d9"],
        ["#fffd88", "#fffd88"],
        ["#108707", "#108707"],
        ["#29dbf8", "#29dbf8"],
        ["#fcbd32", "#fcbd32"],
        ["#fa5356", "#fa5356"],
        ["#ee76fc", "#ee76fc"],
        ["#89f480", "#89f480"],
        ["#f38053", "#f38053"],
        ["#25b5b0", "#25b5b0"],
      ],
    };
  },
  created() {},
  watch: {
    data: {
      handler(newValue, old) {
        this.options.data = { ...newValue };
        const firstKey = Object.keys(newValue.barData)[0];
        this.options.data.currentData = newValue.barData[firstKey]
          ? newValue.barData[firstKey].map((item, index) => {
              return {
                name: item.name,
                data: [item.value],
                color: this.colors[index],
                stack: "total",
              };
            })
          : [];
        this.$nextTick(() => {
          this.chart.setOption(PieBarOptions({ ...this.options }), true, true);
        });
      },
      deep: true,
    },
  },
  props: {
    data: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {
    this.options = {
      data: this.data,
    };
    this.chart = this.$echarts.init(this.$refs["pieBar"]);
    this.chart.setOption(PieBarOptions({ ...this.options }), true, true);

    // 当鼠标在饼图时，高亮显示柱状图
    this.chart.on("click", (param) => {
      if (param.seriesType === "pie") {
        let arr = [];
        this.options.data.barData[param.name].forEach((item, index) => {
          arr.push({
            name: item.name,
            data: [item.value],
            color: this.colors[index],
            stack: "total",
          });
        });
        this.options.data.currentData = arr;
        this.chart.setOption(PieBarOptions({ ...this.options }), true, true);
      }
    });
    resizeChart(this.chart);
  },
};
</script>
<style scoped>
.pie-bar {
  height: 100%;
  width: 100%;
}
</style>
